<!DOCTYPE html>
<html>
  <head>
    <script>
      // The last url with book id.
      var last_url = "";

      // Called when a message is passed.  We assume that the content script
      // wants to show the page action.
      function onRequest(request, sender, sendResponse) {
        last_url = request["url"];
 
        // Show the page action for the tab that the sender (content script)
        // was on.
        chrome.pageAction.show(sender.tab.id);

        // Return nothing to let the connection be cleaned up.
        sendResponse({});
      };

      // Listen for the content script to send a message to the background page.
      chrome.extension.onRequest.addListener(onRequest);
      
      // Do nothing
      function doneCreatingTab(tab) {
      }

      // Handle a click on the extension icon.
      function handleClick() {
         // URL like: http://library.ci.mtnview.ca.us/search~S0?/c782.1092+WAGNER+Cambridge/c782.1092+wagner+cambridge/-3,-1,,B/browse
         var my_last_url = decodeURI(chrome.extension.getBackgroundPage().last_url);
         // Find /c<anything but /><numbers><dot><numbers><anything but />/ which is always part of the url
         var regex = /\/c[^/]*\d+\.\d+[^/]+\//;
         if (regex.test(my_last_url)) {
            var items = my_last_url.match(regex);
            // This will be like /c782.1029+A+B+C/, so if we split by / the middle item will contain the string.
            var almost_clean = items[0].split('/');
            // Remove c, and ? and everything after, including the first +
            var clean = almost_clean[1].replace('c', '').replace(/\+/, ' ').replace('?', '').replace(/\+.*/, '');
            // Create a new tab with the map for the current book call number
            chrome.tabs.create({ url: "http://localhost/~annie/map/map.html#" +  encodeURI(clean) }, doneCreatingTab);
         } else {
            var regex2 = /\/c[A-Z][A-Z+]+\d*\//;
            var items = my_last_url.match(regex2);
            // This will be like /cJ+GN+SNOW+Powell/ or /cDVD+CINDERELLA+2007/
            var almost_clean = items[0].split('/');
            var clean = almost_clean[1].replace('c', '').replace(/\+/g, ' ');
            chrome.tabs.create({ url: "http://localhost/~annie/map/map.html#" +  encodeURI(clean) }, doneCreatingTab);
         }
      };

      // Add event handler for clicks on the extension icon
      chrome.pageAction.onClicked.addListener(handleClick);
</script>
</head>
</html>
